import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/layout/index.vue'
import Home from '@/views/home/index.vue'
import Categroy from '@/views/category/index.vue'
import CategroySub from '@/views/category/sub.vue'
import Goods from '@/views/goods/index.vue'
import useStore from '@/store'
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          component: Home,
        },
        {
          path: '/category/:id', // 一级分类路由
          component: Categroy,
        },
        {
          path: '/category/sub/:id', // 二级分类路由
          component: CategroySub,
        },
        {
          path: '/goods/:id', // 商品详情
          component: Goods,
        },
        {
          path: '/cart', // 商品详情
          component: () => import('@/views/cart/index.vue'),
        },
        {
          path: '/member/checkout',
          component: () => import('@/views/member/pay/checkout.vue'),
        },
        {
          path: '/member/pay',
          component: () => import('@/views/member/pay/index.vue'),
        },
        {
          path: '/pay/callback',
          component: () => import('@/views/member/pay/callback.vue'),
        },
        {
          path: '/member',
          component: () => import('@/views/member/layout/index.vue'),
          children: [
            {
              // 个人中心
              path: '',
              component: () => import('@/views/member/home/index.vue'),
            },
            {
              // 我的订单
              path: 'order',
              component: () => import('@/views/member/order/index.vue'),
            },
          ],
        },
      ],
    },
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
    },
    {
      path: '/playground',
      component: () => import('@/views/playground/index.vue'),
    },
    // 绑定路由 (一级路由)
    {
      path: '/login/callback',
      component: () => import('@/views/login/callback.vue'),
    },
  ],
  scrollBehavior: () => ({
    top: 0,
  }),
})

// 配置路由导航守卫，拦截 /member 开头的所有的地址
router.beforeEach((to, from, next) => {
  // 判断用户登没登录
  const { cart } = useStore()
  if (cart.isLogin) {
    // 已登录就放行
    next()
  } else {
    if (to.path.includes('/member')) {
      next({
        path: '/login',
        // 增加回跳的 url 地址
        query: {
          // 目的是为了下次登录能回到原页面
          redirectUrl: to.fullPath,
        },
      })
    } else {
      next()
    }
  }
})

export default router
